<template>
  <Card :bordered="false">
    <p slot="title">
      <Icon type="logo-buffer"></Icon>
      文件管理
    </p>
    <a href="#" v-if="permission.file_upload === '1'" slot="extra" @click.prevent="fileUploadModal">
      <Icon type="md-add-circle"></Icon>
      上传
    </a>
    <Modal v-model="uploadModal" mask :mask-closable="false" scrollable title="上传文件">
      <div>
        <Row>
          <Col span="8">
            <Upload
              :headers="auth"
              :data="post_data"
              :show-upload-list="false"
              multiple
              ref="upload"
              :on-success="uploadSuccess"
              :on-error="uploadError"
              :before-upload="handleUpload"
              action="//192.168.10.204:8000/files/upload/">
              <Button type="info" icon="ios-cloud-upload-outline">选择文件</Button>
            </Upload>
            <div v-for="(file_value,index) in file" :key="index">{{ file_value.name }} </div>
          </Col>
          <Col span="8">
            <Button type="success" @click="upload" :loading="loadingStatus">{{ loadingStatus ? '正在上传，请稍候...' : '点击上传' }}</Button>
          </Col>
        </Row>
      </div>
      <!-- 自定义页眉按键 -->
      <div slot="close"></div>
      <!-- 自定义页脚按键 -->
      <div slot="footer">
        <Button type="default" @click="statusView">查看状态</Button>
        <Button type="default" @click="restUploadList">清空</Button>
        <Button type="default" style="margin-right: 5px" @click="closeUploadView">关闭</Button>
      </div>
    </Modal>
    <div style="padding-bottom: 10px;">
      <Row :gutter="16">
        <Col span="10">
          <Select v-model="file_type" style="width:240px;padding-right:10px" placeholder="请选择文件类型" clearable @on-change="handFileList" ref="file_type_select">
            <Option v-for="item in selec_env_men" :value="item.value" :key="item.value">{{ item.label }}</Option>
          </Select>
          <Select v-if="file_type=='app'" v-model="env_name" style="width:200px" placeholder="请选择上传环境" clearable @on-change="handFileList" ref="env_select">
            <Option v-for="item in envList" :value="item.value" :key="item.value">{{ item.label }}</Option>
          </Select>
          <Select v-if="file_type=='image'" v-model="image_type" style="width:200px" placeholder="请选择图片类型" clearable @on-change="handFileList" ref="image_select">
            <Option v-for="item in image_type_list" :value="item.value" :key="item.value">{{ item.label }}</Option>
          </Select>
        </Col>
        <Col span="6" offset="8">
          <Input search placeholder="Search ..." v-model="searchValue" @on-search=searchFile />
        </Col>
      </Row>
    </div>
  <div>
    <Table :border=false :columns="columns" :data="data">
      <template slot-scope="{ row, index }" slot="index">
        <span>{{index+1}}</span>
      </template>
      <template slot-scope="{ row, index }" slot="action">
        <Button type="success" v-clipboard="row.file_url" @success="handleSuccess" @error="handleError" size="small" style="margin-right: 5px">拷贝URL</Button>
        <Button v-if="permission.file_delete === '1'" type="error" size="small" @click="remove(index)">删除</Button>
      </template>
    </Table>
    <div style="padding-top: 10px;" v-if="count">
      <template>
        <Page :total="count" show-total :page-size-opts="[10,25,40,55,70,100]" current.sync="current" show-elevator show-sizer  @on-change="switchPage" @on-page-size-change="switchPageSize" />
      </template>
    </div>
  </div>
</Card>
</template>
<script>
import { getToken } from '@/libs/util'
import { fileList, fileAllSearch, deleteFile } from '@/api/files'

  export default {
    data () {
      return {
        permission: '',
        file_type: '',
        env_name: '',
        image_type: '',
        page: 1,
        page_size: 10,
        searchValue: '',
        uploadModal: false,
        auth: null,
        post_data: null,
        file: [], // 总文件List
        uploadFile: [], // 需要上传的文件List
        upload_success_res: [], //上传成功的文件
        loadingStatus: false,
        uploadStaus: '',
        envList: [{'value':'stg','label':'预发环境'},{'value':'prod','label':'生产环境'}],
        image_type_list: [
          {'value':'banner','label':'banner'},
          {'value':'icon','label':'icon(图标)'},
          {'value':'national','label':'national(国旗)'},
          {'value':'partners','label':'partners(合作商)'},
          {'value':'other','label':'other(其它)'}
        ],
        data: [],
        count: null,
        selec_env_men: [
          {'value':'app','label':'APP'},
          {'value':'image','label':'图片'},
          {'value':'andio','label':'音频'},
          {'value':'video','label':'视频'},
          {'value':'other','label':'其它'}
        ],
        columns: [
          {
            title: '序号',
            slot: 'index',
            width: '60',
            align: 'center'
          },
          {
            title: '名称',
            key: 'name',
          },
          {
            title: 'url地址',
            key: 'file_url',
            // slot: 'file_url'
          },
          {
            title: '文件MD5',
            key: 'file_md5',
            align: 'center'
          },
          {
            title: '上传时间',
            key: 'create_time',
            align: 'center'
          },
          {
            title: '操作',
            slot: 'action',
            width: 240,
            align: 'center'
          }
        ]
      }
    },
    created () {
      this.get_permission()
    },
    methods: {
      // 获取用户操作权限
      get_permission () {
        const auth = JSON.parse(sessionStorage.getItem('permission'))
        this.permission = auth.child
      },
      //获取文件列表
      handFileList () {
        if (this.file_type === 'app') {
          if (this.env_name.length != 0) {
            fileList(this.env_name,this.file_type,this.file_type,this.page,this.page_size).then(res => {
              this.count = res.data.count
              this.data = res.data.results
            })
          }
        } else if ( this.file_type === 'image') {
          if ( this.image_type.length != 0 ) {
            this.env_name = 'prod'
            fileList(this.env_name,this.file_type,this.image_type,this.page,this.page_size).then(res => {
              this.count = res.data.count
              this.data = res.data.results
            })
          }
        } else if ( this.file_type != 'app' || this.file_type != 'image') {
          this.env_name = 'prod'
          fileList(this.env_name,this.file_type,this.file_type,this.page,this.page_size).then(res => {
            this.count = res.data.count
            this.data = res.data.results
          })
        }
      },
      fileUploadModal () {
        if (this.file_type.length != 0) {
          if (this.file_type === 'app' && this.env_name.length === 0){
            this.$Message.warning("上传APP需要指定上传环境！")
            return false
          }
          if (this.file_type == 'app' && this.env_name == 'stg'){
            this.$Message.warning({content:"暂不支持预发布环境!",duration: 5,closable: true})
            return false
          }
          if ( this.file_type === 'image' && this.image_type.length === 0 ) {
            this.$Message.warning("上传图片需要指定图片类型!")
            return false
          }
          this.uploadModal = true;
          const token = getToken();
          this.auth = {'Authorization': 'JWT ' + getToken()};
          if ( this.file_type === 'image' ) {
            this.post_data = {'env':this.env_name,'file_type':this.file_type,'child_type':this.image_type};
          } else {
            this.post_data = {'env':this.env_name,'file_type':this.file_type};
          }
          this.uploadStaus = null;  //设置上传的状态为空
          this.file = []; //清空总文件列表
          this.uploadFile = []; //清空需要上传的文件列表
          this.upload_success_res = []; //清空上一次上传的文件列表
        }else {
          this.$Message.warning("请选择文件类型！")
        }
      },
      // 上传文件之前的钩子
      handleUpload (file) {
        let keyID = Math.random().toString().substr(2);
        file['keyID'] = keyID;
        this.file.push(file);
        this.uploadFile.push(file);
        this.uploadStaus = 'waiting';
        return false
      },
      // 上传
      upload () {
        if (this.uploadFile.length === 0) {
            this.$Message.error('未选择上传文件')
            return false
          }
          this.loadingStatus = true;
          this.uploadStaus = 'uploading';
          for (let i = 0; i < this.uploadFile.length; i++) {
            let item = this.file[i]
            this.$refs.upload.post(item);
          }
      },
      uploadSuccess(response, file, fileList) {   // 文件上传回调 上传成功后删除待上传文件
        this.upload_success_res.push(file['name'])
        // 根据上传成功的文件数量和文件总数量进行对比，以确定文件是否完全上传成功。并取消loading加载
        if (this.upload_success_res.length === this.file.length) {
          this.loadingStatus = false;
          this.uploadStaus = 'success';
          this.$Message.success({content:'上传完成!',duration: 10,closable: true});
          //更新数据
          this.handFileList()
        }
        // console.log(response) // 后端返回数据
        // console.log(file) // 当前上传文件
        // console.log(fileList) // 整个input file 里的文件数组
      },
      uploadError (error,file,fileList) {
        console.log(error)
        this.uploadStaus = 'error';
        this.loadingStatus = false
        this.$Message.error({content:'上传失败!',duration: 60,closable: true})
      },
      //关闭文件上传窗口
      closeUploadView () {
        if (this.loadingStatus === false) {
          this.uploadModal=false
        } else {
          this.$Message.warning("请等待文件上传结果!")
        }
      },
      // 清空文件列表
      restUploadList () {
        if (this.loadingStatus === false) {
          this.uploadStaus = null;
          this.file = [];
          this.uploadFile = [];
          this.upload_success_res = [];
        } else {
          this.$Message.warning("请等待文件上传结果!")
        }
      },
      //查看状态
      statusView () {
        if (this.uploadStaus === null) {
          this.$Message.info("没有可供上传的文件!")
        } else if (this.uploadStaus === 'waiting') {
          this.$Message.warning("等待上传!")
        } else if (this.uploadStaus === 'success') {
          this.$Message.warning("上述文件已上传成功!") 
        } else if (this.uploadStaus === 'error') {
          this.$Message.error("文件上传失败!")
        } else {
          this.$Message.warning("文件正在上传中，请稍候...")
        }
      },
      //搜索文件
      searchFile () {
        if (this.file_type.length != 0) {
          if (this.file_type === 'app' && this.env_name.length ===0) {
            this.$Message.warning({content:'搜索APP文件需要指定其上传环境！',duration: 10,closable: true})
            return false
          }
          fileAllSearch(this.env_name, this.file_type,this.searchValue).then(res => {
            this.data = res.data.results
            this.count = res.data.count
          }).catch(err => {
            this.$Message.error('接口请求失败!')
          })
        } else {
          this.$Message.error("请选择文件类型!")
        }
      },
      // 获取页码并发起请求
      switchPage (page) {
        this.page = page
        if ( this.file_type === 'image') {
          var child_type = this.image_type
        } else {
          var child_type = this.file_type
        }
        fileList(this.env_name, this.file_type, child_type, this.page, this.pageSize, this.searchValue).then(res => {
          this.data = res.data.results
        }).catch(err => {
          this.$Message.error('接口请求失败')
        })
      },
      // 获取选择切换的每页条数并发起请求
      switchPageSize (pageSize) {
        this.page = 1
        this.page_size = pageSize
        if ( this.file_type === 'image') {
          var child_type = this.image_type
        } else {
          var child_type = this.file_type
        }
        fileList(this.env_name,this.file_type,child_type, this.page,this.page_size,this.searchValue).then(res => {
          this.count = res.data.count
          this.data = res.data.results
        }).catch(err => {
          this.$Message.error('接口请求失败')
        })
      },
      handleSuccess(e) {
        this.$Message.success('复制成功')
      },
      handleError(e) {
        this.$Message.error("复制出错！")
      },
      remove (index) {
        if ( this.file_type === 'image') {
          var child_type = this.image_type
        } else {
          var child_type = this.file_type
        }
        deleteFile(this.data[index].id).then(res => {
          this.data.splice(index, 1);
          fileList(this.env_name, this.file_type,child_type, this.page, this.page_size, this.searchValue).then(res => {
            this.data = res.data.results
            this.count = res.data.count
            this.$Message.success({content:'删除成功!',duration: 5,closable: true})
          }).catch(err => {
            this.$Message.error('接口请求失败')
          })
        }).catch(err => {
          this.$Message.error({content:'删除失败!',duration: 5,closable: true})
        })
      }
    }
  }
</script>